import * as vscode from "vscode";
import { colors } from "./colors";
import { mirServer, MirServerProvider } from "./extension";

class ColorCompletionItem extends vscode.CompletionItem {
  constructor(color: (typeof colors)[number]) {
    super(color.number, vscode.CompletionItemKind.Color);
    this.detail = color.hex;
    this.documentation = color.number;
    this.insertText = color.number;
    this.filterText = color.number;
    this.sortText = color.number;
  }
}

class ColorsCompletionList extends vscode.CompletionList {
  constructor(list: typeof colors) {
    super(
      list.map((color) => new ColorCompletionItem(color)),
      true
    );
  }
}

export class ColorsCompletionItemProvider implements vscode.CompletionItemProvider<ColorCompletionItem> {
  isCommandTriggered: boolean = false;
  triggerSuggest() {
    this.isCommandTriggered = true;
    // 执行两步操作：
    vscode.commands.executeCommand("editor.action.triggerSuggest").then(() => {
      // 重置状态（延迟确保补全列表弹出）
      setTimeout(() => (this.isCommandTriggered = false), 500);
    });
  }

  validatorColorDocument(text: string) {
    const validators = [() => /color=\s*$/i.test(text), () => /autocolor=(\d+,)*$/i.test(text)];
    return validators.some((validator) => validator());
  }
  provideCompletionItems(
    document: vscode.TextDocument,
    position: vscode.Position,
    token: vscode.CancellationToken,
    context: vscode.CompletionContext
  ): vscode.ProviderResult<ColorCompletionItem[] | vscode.CompletionList<ColorCompletionItem>> {
    const linePrefix = document.lineAt(position).text.slice(0, position.character);
    if (!this.validatorColorDocument(linePrefix) && !this.isCommandTriggered) {
      return undefined;
    }
    return new ColorsCompletionList(colors);
  }
}

export class ColorQuickPicker implements MirServerProvider {
  activate() {
    const provider = new ColorsCompletionItemProvider();
    mirServer.context.subscriptions.push(
      vscode.languages.registerCompletionItemProvider("mirtxt", provider, "=", ","),
      vscode.commands.registerCommand("mir-script-language.show-color-picker", () => provider.triggerSuggest())
    );
  }
}
